package com.yuanfeng.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.PayToolUtil;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.payment.common.PayCommonUtils;
import com.yuanfeng.payment.dto.AssetTmpInfoDTO;
import com.yuanfeng.payment.entity.PayConsumeTradeEntity;
import com.yuanfeng.payment.entity.PayUserResourceEntity;
import com.yuanfeng.payment.service.PayConsumeTradeService;
import com.yuanfeng.payment.service.PayStrategyHandleService;
import com.yuanfeng.payment.service.PayUserResourceService;
import com.yuanfeng.payment.vo.CallBackVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物卡支付
 *
 * @author Stranger
 * @date 2023/4/27 11:39
 */
@Service
public class GiftCardPayServiceImpl implements PayStrategyHandleService {


    private static PayCommonUtils payCommonUtils;


    private static PayConsumeTradeService payConsumeTradeService;


    private static PayUserResourceService payUserResourceService;

    final Logger log = LoggerFactory.getLogger(GiftCardPayServiceImpl.class);


    // 注入的时候，给类的 service 注入
    @Autowired
    public void setPayUserResourceService(PayUserResourceService payUserResourceService) {
        GiftCardPayServiceImpl.payUserResourceService = payUserResourceService;
    }

    // 注入的时候，给类的 service 注入
    @Autowired
    public void setPayCommonUtils(PayCommonUtils payCommonUtils) {
        GiftCardPayServiceImpl.payCommonUtils = payCommonUtils;
    }

    // 注入的时候，给类的 service 注入
    @Autowired
    public void setPayConsumeTradeService(PayConsumeTradeService payConsumeTradeService) {
        GiftCardPayServiceImpl.payConsumeTradeService = payConsumeTradeService;
    }

    @Override
    public ResponseResult userPayEntrance(Map<Object, Object> map, HttpServletRequest request, HttpServletResponse response) {

            String token = (String) map.get("token");
            //获取用户信息
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
            //获取用户ID
            String userId = userInfo.getUserId();
            //支付密码
            String passwd = (String) map.get("passwd");
            // 接收付款订单编号
            String orderId = (String) map.get("orderIdList");
            //虚拟订单 0 是 1 否
            Integer virtualGoods = null;
            //门店字体订单
            Integer orderIsShopTake = null;
            // 错误次数
            Integer errorNum = 0;
            Map<Object, Object> assetDetailMap = new HashMap<>();
            //获取用户账号信息
            PayUserResourceEntity payUserResourceEntity = payUserResourceService.getById(userInfo.getUserId());

            Map<String, String> orderIdIsNum = new HashMap<>();
            orderIdIsNum.put("orderId", orderId);
            String paymentNumber = orderId;
            if (null != paymentNumber) {
                if (paymentNumber.contains("[")) {
                    paymentNumber = paymentNumber.replace("[", "");
                }
                if (paymentNumber.contains("]")) {
                    paymentNumber = paymentNumber.replace("]", "");
                }
            }
            // 1:余额支付  2:购物卡支付
            if (RedisUtil.exists(YFConfig.DETERMINEWHETHERTOPAY + "-" + orderId + "-" + userInfo.getUserId() + "-" + map.get("type").toString())) {
                //订单已支付，请勿重复支付！
                return ResponseResult.fail(BizCodeEnume.ORDER_PAID);
            }
            //获取订单信息
            ResponseResult responseResult = payCommonUtils.getDeteails(orderId, paymentNumber);
            if (responseResult.getCode() == CommonStatusEnum.FAIL.getCode()) {
                return responseResult;
            }

            List<CallBackVO> callBackParaList = payConsumeTradeService.treasureOrder(token, orderId);
            // 验证支付密码
            Integer isExist = payCommonUtils.getPwdExist(passwd, userInfo).getCode();
            if (isExist == 1) {
                BigDecimal amountActuallyPaids = new BigDecimal(0);
                Integer amountAotalIntegral = null;
                //积分商品 0  是  1 否
                Integer integralGoods = 1;
                // 查询此订单
                if (PayToolUtil.isInteger(orderId)) {
                    PayConsumeTradeEntity queryGoodsPara = payConsumeTradeService.getOne(new LambdaUpdateWrapper<PayConsumeTradeEntity>()
                            .eq(PayConsumeTradeEntity::getOrderId, orderId));
                    BigDecimal paymentAmount = queryGoodsPara.getTradePaymentAmount();
                    //获取积分商品订单的积分
                    Integer totalIntegral = queryGoodsPara.getTotalIntegral();
                    integralGoods = queryGoodsPara.getIntegralGoods();
                    amountAotalIntegral = totalIntegral;
                    amountActuallyPaids = paymentAmount;
                    //订单号是数字
                    orderIdIsNum.put("isNum", "0");
                } else {
                    // 实付金额
                    String amountActuallyPaid = RedisUtil
                            .get(YFConfig.YF_USERAMOUNTACTUALLYPAID + "--" + token + "--" + userId);
                    // 获取积分商品的积分
                    String totalIntegral = RedisUtil
                            .get(YFConfig.YF_USERINTEGRALYPAID + "--" + token + "--" + userId);
                    if(null==amountActuallyPaid){
                        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
                    }
                    // 类型转换
                    amountActuallyPaids = new BigDecimal(amountActuallyPaid);
                    if (null != totalIntegral) {
                        //amountAotalIntegral 不为null 证明是积分订单
                        amountAotalIntegral = Integer.valueOf(totalIntegral);
                        integralGoods = 0;
                    }
                    //订单号不是数字
                    orderIdIsNum.put("isNum", "1");
                }
                ResponseResult integralResult = payCommonUtils.getUserIntegral(integralGoods, userId, amountAotalIntegral, orderId);
                if (integralResult.getCode() == CommonStatusEnum.FAIL.getCode()) {
                    return integralResult;
                }

                // 查询账户购物卡余额
                BigDecimal userGiftCardMoney = payUserResourceEntity.getUserRechargeCard();
                // 判断实付金额与余额
                if (userGiftCardMoney.compareTo(amountActuallyPaids) == 1
                        || userGiftCardMoney.compareTo(amountActuallyPaids) == 0) {
                    // 扣除购物金额
                    boolean updateMoney = payUserResourceService.update(null,new LambdaUpdateWrapper<PayUserResourceEntity>()
                            .eq(PayUserResourceEntity::getUserId, userInfo.getUserId())
                            .set(PayUserResourceEntity::getUserRechargeCard, payUserResourceEntity.getUserRechargeCard().subtract(amountActuallyPaids)));

                    //支付
                    List<AssetTmpInfoDTO> tmpInfo = JSON.parseArray(JSON.toJSONString(responseResult.getData()), AssetTmpInfoDTO.class);
                    return payCommonUtils.getPay(updateMoney, token, userId, orderId, map.get("type").toString(),
                            virtualGoods, orderIsShopTake, amountActuallyPaids,
                            amountAotalIntegral, orderIdIsNum, callBackParaList,
                            integralGoods, assetDetailMap,  tmpInfo);

                } else {
                    //账户余额不足！
                    return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_ACCOUNT_BALANCE);
                }
            } else {
                errorNum++;
                if (errorNum == 3) {
                    //密码错误三次！
                    return ResponseResult.fail(BizCodeEnume.PASSWORD_ERROR_THREE_TIMES);
                }
                return ResponseResult.fail(BizCodeEnume.PASSWORD_ERROR_TWO);
            }

    }
}
